<template>
	<view class="card tourist-info" v-if="tourist_contact_rule?.each_person">
		<view class="card-top">
			<view class="title">填写游客信息</view>
			<view class="tips">
				用于入园身份验证，还需选择
				<text class="number">{{ count }}</text>
				位
			</view>
		</view>
		<view class="info-block" v-for="(item, index) in touristList" :key="index">
			<InfoDisplay
				:label="`游客${index + 1}`"
				v-model="touristList[index]"
				:idx="index"
				type="tourist"
				:show-name="tourist_contact_rule?.tourist_require_name"
				:show-id="tourist_contact_rule?.tourist_require_id_value"
				:show-mobile="tourist_contact_rule?.tourist_require_mobile"
				@open-popup="openPopup"
			/>
		</view>
		<TouristContact
			type="tourist"
			:show="show"
			:idx="idx"
			@contact-info-change="handleContactInfoChange"
			@close-popup="closePopup"
		/>
	</view>
</template>

<script setup lang="ts">
import type { TouristContactRule } from "@/types/ticket"

interface TouristInfoProps {
	tourist_contact_rule: TouristContactRule
}

import { ref, computed, watch, onMounted } from "vue"
import type { ContactsInfo } from "@/types/ticket"
import InfoDisplay from "./info-display.vue"
import TouristContact from "./tourist-contact.vue"

const props = defineProps<TouristInfoProps>()

const show = ref(false)
const idx = ref()
const touristList = ref<ContactsInfo[]>([])

const count = computed(() => {
	return (
		touristList.value.length -
		touristList.value.filter((item) => Object.values(item || {}).filter(Boolean).length).length
	)
})

watch(
	() => props.tourist_contact_rule?.each_person,
	(val) => {
		touristList.value = new Array(val)
	}
)

const openPopup = (index: number) => {
	idx.value = index

	show.value = true
}

const closePopup = () => {
	idx.value = undefined

	show.value = false
}

const handleContactInfoChange = (info: ContactsInfo) => {
	if (idx.value !== undefined && info) {
		touristList.value[idx.value] = info

		if (idx.value === 0) {
			uni.$emit("first-tourist-info-change", info)
		}
	}
}

onMounted(() => {
	uni.$on("amount-add", () => {
		touristList.value = [...touristList.value, ...new Array(props.tourist_contact_rule?.each_person)]
	})

	uni.$on("amount-subtract", () => {
		touristList.value = touristList.value.slice(
			0,
			touristList.value.length - props.tourist_contact_rule?.each_person
		)
	})
})

defineExpose({
	touristList,
})
</script>

<style lang="scss" scoped>
@import "../ticket/index.scss";

.tourist-info {
	padding-bottom: 0;
}

.card-top {
	display: flex;
	align-items: center;

	.tips {
		margin-left: 8rpx;
		font-size: 24rpx;
		color: #86909c;
		line-height: 34rpx;

		.number {
			color: #bc8400;
		}
	}
}

.title {
	font-weight: 600;
	font-size: 32rpx;
	color: rgba(0, 0, 0, 0.9);
	line-height: 52rpx;
}

.info-block {
	border-bottom: 1rpx solid #f3f3f3;

	&:last-child {
		border-bottom: none;
	}
}
</style>
